//
//  HSDSpidermanPageHelper.m
//  GoldenCard
//
//  Created by 正合适 on 2018/3/21.
//  Copyright © 2018年 合时代. All rights reserved.
//

#import "HSDSpidermanPageHelper.h"
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
#import "HSDSpidermanTools.h"
#import "HSDSpiderMacro.h"
#import "HSDSpidermanCache.h"
#import <MJExtension/MJExtension.h>
#import "HSDSpidermanPageData.h"

#define kInstanceAss @"instanceMeroryAddress"
// 页面行为结束
NSString *const kPageRouteEndNotify = @"com.hsd.spiderman.routepageendnotify";

@interface HSDSpidermanPageHelper ()
/**页面*/
@property (nonatomic, strong) NSMutableArray<HSDSpidermanPageModel *> *pageArr;

@end

@implementation HSDSpidermanPageHelper
- (instancetype)init {
    self = [super init];
    if (self) {
        [self index];
    }
    return self;
}

#pragma mark - 入口
- (void)index {
    _pageArr = [NSMutableArray array];
    
    [self addObservers];
}

#pragma mark - 监听
- (void)addObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeAction) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackgroundAction) name:UIApplicationDidEnterBackgroundNotification object:nil];
}

- (void)pageDurationWithModel:(HSDSpidermanPageModel *)model {
    if (model.pageStartTime.length > 0 && model.pageEndTime.length > 0) {
        NSInteger duration = model.pageEndTime.integerValue - model.pageStartTime.integerValue;
        model.duration = [NSString stringWithFormat:@"%ld",duration];
    } else {
        model.duration = @"";
    }
}

#pragma mark - 界面进入
- (void)pageEnterWithObject:(NSDictionary *)objectInfo {
    /*
    [self addModelWithObject:object];
    // 进入界面后，判断是否为行为结束
    if (_pageArr.count > 1) {
        HSDSpidermanPageModel *firstModel = _pageArr.firstObject;
        id firstInstance = objc_getAssociatedObject(firstModel, kInstanceAss);
        if (firstInstance == object) {
            [self endRouteWithType:RouteEndType_BackStartPage];
        }
    }
     */
    [self addModelWithObject:objectInfo];
    if (_pageArr.count > 1) {
        HSDSpidermanPageModel *firstModel = _pageArr.firstObject;
        NSDictionary *firstInstanceInfo = objc_getAssociatedObject(firstModel, kInstanceAss);
        NSString *firstAddress = firstInstanceInfo[@"address"];
        NSString *objAddress = objectInfo[@"address"];
        if ([firstAddress isEqualToString:objAddress]) {
            [self endRouteWithType:RouteEndType_BackStartPage];
        }
    }
}

#pragma mark - 界面离开
- (void)pageLeaveWithObject:(id)object {
    HSDSpidermanPageModel *model = _pageArr.lastObject;
//    for (HSDSpidermanPageModel *model in _pageArr) {
//        id instance = objc_getAssociatedObject(model, kInstanceAss);
//        if (instance == object) {
//            model.pageEndTime = currentTime();
//            [self pageDurationWithModel:model];
//        }
//    }
    model.pageEndTime = currentTime();
    [self pageDurationWithModel:model];
}

#pragma mark - 当前vc是否存在数组中
//- (BOOL)isExistWithObject:(id)object block:(void(^)(HSDSpidermanPageModel *model))block {
//    UIViewController *vc = (UIViewController *)object;
//    for (HSDSpidermanPageModel *model in _pageArr) {
//        id instance = objc_getAssociatedObject(model, kInstanceAss);
//        if (instance == vc) {
//            if (block) block(model);
//            return YES;
//        }
//    }
//    return NO;
//}

#pragma mark - 在数组中添加节点数据
- (void)addModelWithObject:(NSDictionary *)objectInfo {
    NSString *time = currentTime();
//    UIViewController *vc = (UIViewController *)object;
    HSDSpidermanPageModel *referModel = nil;
//    if (_pageArr.count > 0) referModel = _pageArr.lastObject;
    if (_pageArr.count > 0) {
        referModel = _pageArr.lastObject;
        referModel.pageEndTime = time;
        [self pageDurationWithModel:referModel];
    }
    HSDSpidermanPageModel *model = [[HSDSpidermanPageModel alloc] init];
    objc_setAssociatedObject(model, kInstanceAss, objectInfo, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//    model.pageStartTime = currentTime();
    model.pageStartTime = time;
    model.pageId = objectInfo[@"className"];
    model.referPageId = referModel?referModel.pageId:@"";
    [_pageArr addObject:model];
}

#pragma mark - 行为结束
- (void)endRouteWithType:(RouteEndType)type {
    if (_pageArr.count <= 1) {
        [_pageArr removeAllObjects];
        return;
    }
    NSString *time = currentTime();
    HSDSpidermanPageModel *last = _pageArr.lastObject;
    last.pageEndTime = time;
    [self pageDurationWithModel:last];
    HSDSpidermanPageData *data = [HSDSpidermanPageData new];
    data.page = _pageArr.mutableCopy;
    NSString *jsonStr = data.mj_JSONString;
    [[NSNotificationCenter defaultCenter] postNotificationName:kPageRouteEndNotify object:jsonStr userInfo:@{@"type":@(type)}];
    [_pageArr removeAllObjects];
    last.pageStartTime = time;
    [_pageArr addObject:last];
}

#pragma mark - app启动Action
- (void)applicationDidBecomeAction {
    [_pageArr removeAllObjects];
    UIViewController *vc = [HSDSpidermanTools topViewController];
    if (vc && [vc isKindOfClass:[UIViewController class]]) {
        NSString *memoryAddress = [NSString stringWithFormat:@"%p",vc];
        [self addModelWithObject:@{@"className":instanceClassName(vc),@"address":memoryAddress}];
    }
}

#pragma mark - 进入后台
- (void)applicationDidEnterBackgroundAction {
    [self performSelector:@selector(backgroundAction) onThread:_mainThread withObject:nil waitUntilDone:YES];
}

- (void)backgroundAction {
    [self endRouteWithType:RouteEndType_Background];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
